package cn.wolfcode.trip.admin.web.controller;

import cn.wolfcode.trip.admin.web.util.UploadUtil;
import cn.wolfcode.trip.base.domain.Commodity;
import cn.wolfcode.trip.base.query.CommodityQueryObject;
import cn.wolfcode.trip.base.service.ICommodityService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/commodity")
public class CommodityController {
    @Autowired
    private ICommodityService commodityService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo")CommodityQueryObject qo,Model model){
        qo.setOrderBy("create_time desc");
        model.addAttribute("result", commodityService.query(qo));
        return "commodity/list";
    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Commodity commodity, MultipartFile pic){
        JSONResult result = new JSONResult();
        try {
            if (pic != null && pic.getSize() > 0) {
                String imagePath = UploadUtil.upload(pic, UploadUtil.IMG_PATH + "upload");
                commodity.setPicture(imagePath);
            }
            commodityService.saveOrUpdate(commodity);
        }catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

}
